package com.shop.servlet;

import com.shop.model.CartItem;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@WebServlet("/remove")
public class RemoveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        try {
            String courseId = req.getParameter("courseId");
            HttpSession session = req.getSession();
            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
            if(cart != null){
                Iterator<CartItem> iterator = cart.iterator();
                while(iterator.hasNext()){
                    CartItem item = iterator.next();
                    if (Objects.equals(item.getCourse().getCourseId(), courseId)) {
                        iterator.remove();
                        break;
                    }
                }
            }
            resp.sendRedirect("cart.jsp");
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
